package cn.com.cetccst.compliancecheck.checker;

import static cn.com.cetccst.tools.kv.CommonKV.kvStore;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;

import com.permissionx.guolindev.PermissionX;

import java.util.List;

import cn.com.cetccst.compliancecheck.R;
import cn.com.cetccst.compliancecheck.kv.KVKeys;
import cn.com.cetccst.tools.log.CommonLogger;

public class SIMCardChecker extends Checker {

    private static SIMCardChecker instance;

    private final BroadcastReceiver simUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) return;
            String action = intent.getAction();
            if (action == null || action.isEmpty()) return;

            checkSimResult(context);

            //状态发生变化，重新持久化
            CheckerManager.getInstance().saveChecker(SIMCardChecker.this);
        }
    };

    private SIMCardChecker(Context context) {
        super(CheckerType.SIMCard);
        name = context.getString(R.string.compliance_SIM);
        startMonitor(context);
    }

    public static void init(Context context) {
        if (instance == null) {
            instance = new SIMCardChecker(context);
        }
    }

    public static SIMCardChecker getInstance() {
        return instance;
    }

    @Override
    public void check(Context context) {
        checkSimResult(context);
    }

    private void checkSimResult(Context context) {
        super.check(context);
        if (!isEnable()) {
            return;
        }
        SimState state = getSimState(context);
        setResult(state.isViolated ? CheckResult.Violated : CheckResult.Pass);
    }

    private void startMonitor(Context context) {
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.intent.action.SIM_STATE_CHANGED");
        filter.addAction("android.telephony.action.SIM_CARD_STATE_CHANGED");
        filter.addAction("android.telephony.action.SIM_APPLICATION_STATE_CHANGED");
        context.registerReceiver(simUpdateReceiver, filter);
    }

    private SimState getSimState(Context context) {
        SubscriptionManager sm = SubscriptionManager.from(context);
        if (PermissionX.isGranted(context, Manifest.permission.READ_PHONE_STATE)) {
            List<SubscriptionInfo> sis = sm.getActiveSubscriptionInfoList();
            if (sis == null || sis.isEmpty()) {
                return SimState.ABSENT;
            } else {
                SubscriptionInfo firstSimInfo = sis.get(0);
                String firstSimIccId = firstSimInfo.getIccId();
                String enrolledIccId = kvStore.decodeString(KVKeys.KEY_ENROLLED_ICC_ID);
                if (!enrolledIccId.equals(firstSimIccId)) {
                    CommonLogger.warn("user has inserted a new sim");
                    return SimState.NEW_SIM;
                } else {
                    if (firstSimInfo.getSimSlotIndex() != 0) {
                        CommonLogger.warn("user has changed sim slot " + firstSimInfo.getSimSlotIndex());
                        return SimState.CHANGE_SLOT;
                    }
                }
                if (sis.size() >= 2) {
                    return SimState.BOTH_SIM;
                }
                return SimState.NORMAL;
            }
        }
        return SimState.UNKNOWN;
    }

    public enum SimState {

        UNKNOWN(false, R.string.sim_unknown),
        NORMAL(false, R.string.sim_normal),
        ABSENT(true, R.string.sim_absent),
        NEW_SIM(true, R.string.sim_new_card),
        CHANGE_SLOT(true, R.string.sim_new_slot),
        BOTH_SIM(true, R.string.sim_both_use);

        final boolean isViolated;
        final int msgId;

        SimState(boolean isViolated, int msgId) {
            this.isViolated = isViolated;
            this.msgId = msgId;
        }
    }
}
